<?php
class MySQL
{
    private $servername = "8.130.29.43";
    private $username = "root";
    private $password = "zj20020427";
    private $dbname = "BlueSpace";

    # 连接Mysql数据库
    function connect()
    {
        $conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
        if ($conn->connect_error) {
            die("连接失败： " . $conn->connect_error);
        }
        return $conn;
    }

    # 转换坐标
    public function trans_gis($longitude_latitude)
    {
        $url = "https://restapi.amap.com/v3/assistant/coordinate/convert?locations={$longitude_latitude}&coordsys=gps&key=e2043f0ab803f1d78e8372ee124630c9";

        $res = file_get_contents($url);

        $json_dict = json_decode($res, true);

        //echo  $json_dict['locations'];

        return $json_dict['locations'];
    }

    # 查询用户是否存在
    public function is_user($key)
    {
        $conn = $this->connect();
        // 执行查询的代码
        $sql = "select ID from Users where user_key='$key';";
        $result = $conn->query($sql);
        if ($result) {
            return true;
        } else {
            echo "失败： " . $conn->error;
            return false;
        }
        $conn->close();
    }

    #用户登录逻辑
    public function login($account, $password)
    {
        $conn = $this->connect();
        // 执行查询的代码
        $sql = "select user_key from Users where links='$account' and user_key='$password';";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            // 获取第一条记录
            $row = $result->fetch_assoc();
            // 输出记录
            return $row["user_key"];
        } else {
            return false;
        }
        $conn->close();
    }

    # 查询用户ID
    public function get_userId($key)
    {
        $conn = $this->connect();
        // 执行查询的代码
        $sql = "select ID from Users where user_key='$key';";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            // 获取第一条记录
            $row = $result->fetch_assoc();
            // 输出记录
            return $row["ID"];
        } else {
            return false;
        }
        $conn->close();
    }

    # 查询用户名称
    public function get_username($key)
    {
        $conn = $this->connect();
        // 执行查询的代码
        $sql = "select name from Users where user_key='$key';";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            // 获取第一条记录
            $row = $result->fetch_assoc();
            // 输出记录
            return $row["name"];
        } else {
            return false;
        }
        $conn->close();
    }

    # 查询用户手机号是否已经注册
    public function get_phone($phone)
    {
        $conn = $this->connect();
        // 执行查询的代码
        $sql = "select ID from Users where links='$phone';";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            return true;
        } else {
            return false;
        }
        $conn->close();
    }

    # 新增一个用户
    function add_user($name, $age, $address, $links, $key)
    {

        $conn = $this->connect();
        // 构建插入语句
        $sql = "INSERT INTO Users VALUES (NULL,'$name',$age,'$address','$links','$key');";
        // 执行插入操作
        if ($conn->query($sql) === TRUE) {
            //echo "新记录插入成功";
            return true;
        } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
            return false;
        }
        $conn->close();
    }


    # 创建位置表
    function create_location($tableName)
    {
        $conn = $this->connect();
        $tableName = $tableName . "_location";
        $sql = "CREATE TABLE IF NOT EXISTS $tableName (
                    ID int AUTO_INCREMENT PRIMARY KEY,
                    Longitude VARCHAR(255),
                    Latitude VARCHAR(255),
                    elevation VARCHAR(255),
                    `date` datetime not null,
                    Risk VARCHAR(4) NOT NULL
                )";

        if ($conn->query($sql) === TRUE) {
            //echo "表 $tableName 创建成功";
            return true;
        } else {
            echo "创建表错误： " . $conn->error;
            return false;
        }

        $conn->close();
    }

    # 创建预警区域表
    function create_risk_district($tableName)
    {
        $conn = $this->connect();
        $tableName = $tableName . "_risk_district";
        $sql = "create table if not exists $tableName
        (
        ID int AUTO_INCREMENT PRIMARY KEY,
        Longitude_latiude VARCHAR(255) NOT NULL,
        is_true TINYINT(1) NOT NULL,
        risk_name VARCHAR(20) NOT NULL,
        risk_distance VARCHAR(5) NOT NULL,
        risk_introduce VARCHAR(255),
        images VARCHAR(255),
        distance int
        );";

        if ($conn->query($sql) === TRUE) {
            //echo "表 $tableName 创建成功";
            return true;
        } else {
            echo "创建表错误： " . $conn->error;
            return false;
        }

        $conn->close();
    }
    /*
    # 异常情况表
    function create_warning($tableName)
    {
        $conn = $this->connect();
        $tableName = $tableName . "_warning";
        $sql = "create table if not exists $tableName
        (
        ID int AUTO_INCREMENT PRIMARY KEY,
        warning_key varchar(255) NOT NULL,
        longitude VARCHAR(255),
        latitude VARCHAR(255),
        location VARCHAR(255),
        date datetime NOT NULL,
        distance VARCHAR(255),
        risk VARCHAR(255)
        );	";

        if ($conn->query($sql) === TRUE) {
            //echo "表 $tableName 创建成功";
            return true;
        } else {
            echo "创建表错误： " . $conn->error;
            return false;
        }

        $conn->close();
    }*/
}

# SHA256加密
function sha256($str)
{
    return hash('sha256', $str);
}

# 6位KEY产生
function get_key($length = 6)
{
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

# 新用户统一建立表
function create_table($tablename)
{
    $mysql = new MySQL(); //&& $mysql->create_warning($tablename)
    if ($mysql->create_location($tablename) && $mysql->create_risk_district($tablename)) {
        //创建表全部成功 
        return true;
    } else {
        return false;
    }
}

# 创建新用户函数
function new_user($name, $age, $address, $links)
{
    $mysql = new MySQL();
    if (!($mysql->get_phone($links))) {  # 手机号未被注册
        do {
            $key = get_key();
            $shakey = sha256($key);
        } while (!$mysql->is_user($shakey)); # Key已存在
        # 开始为用户创建数据链
        # 插入用户数据
        $mysql->add_user($name, $age, $address, $links, $shakey);
        # 创建相关信息表
        if (create_table($mysql->get_userId($shakey))) {
            //echo "你的KEY为:" . $key . "，请保存此key，不可更改";
            return $key;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

# 获取get请求
# 创建用户请求
if (isset($_GET['action']) && $_GET['action'] == 'createuser') {
    $mysql = new MySQL();
    $Name = $_GET['Name'];
    $Age = $_GET['Age'];
    $Address = $_GET['Address'];
    $Links = $_GET['Links'];
    # 新增用户及建立相关链表
    $is_create = new_user($Name, $Age, $Address, $Links);
    if ($is_create != false) {
        echo $is_create;
        //echo "用户创建成功，密码Key为：" . $is_create;
    } else {
        echo false;
    }
} elseif (isset($_GET['action']) && $_GET['action'] == 'loginuser') {
    $Account = $_POST['Account'];
    $Password = $_POST['Password'];
    $mysql = new MySQL();
    $user_key = $mysql->login($Account, sha256($Password)); //判别用户登录函数
    if ($user_key) {
        echo $user_key;
    } else {
        echo "false";
    }
}
